/**
 * @Author       : oak-c
 * @Date         : 2021-01-21 13:48:24
 * @Description  :
 * @LastEditors  : oak-c
 * @LastEditTime : 2021-01-21 17:02:13
 * @FilePath     : /src/service/global/help.service.ts
 */
import { GlobalHelpRepo } from '@/entities'
import { IBodyUser, IPagesOption } from '@/interface'
import { CoreException, CoreExceptionType } from '@/modules'
import { timestampFormat } from '@/util'
import { Injectable, OnModuleInit } from '@nestjs/common'

interface Que {
    question: string
    type: number
    imgUrl: string
}

@Injectable()
export class GlobalHelpService implements OnModuleInit {
    constructor(private readonly globalHelpRepo: GlobalHelpRepo) {}

    public async onModuleInit() {
        const defaultQuestion = [
            { question: '如何注册成为用户？', answer: '直接用手机号登录即可，会自动注册。', au: '0000' },
        ]
        for await (const q of defaultQuestion) {
            const exiting = await this.globalHelpRepo.findOne({ question: q.question, au: q.au })
            if (exiting) {
                await this.globalHelpRepo.update(exiting.id, { answer: q.answer })
            } else {
                await this.globalHelpRepo.save(this.globalHelpRepo.create(q))
            }
        }
    }

    /**
     * @description: 查询问题列表
     * @param {object} body
     * @return {*}
     */
    public async queryQuestion(body: { value: string } & IBodyUser & IPagesOption) {
        const { value, __user, current = 1, pageSize = 50 } = body
        const helpBuilder = this.globalHelpRepo.createQueryBuilder()
        if (value) {
            helpBuilder.where('question like :value', { value: `%${value}%` }).andWhere(`answer!=''`)
        } else {
            helpBuilder.where('type=0').orWhere('au=:userid', { userid: __user.userid }).orderBy('type', 'ASC')
        }
        const [list, total] = await helpBuilder
            .skip((current - 1) * pageSize)
            .take(pageSize)
            .getManyAndCount()
        return {
            list,
            total,
            current,
            pageSize,
            count: list.length,
        }
    }

    /**
     * @description: 提交问题
     * @param {Que} body
     * @return {*}
     */
    public async submitQuestion(body: Que & IBodyUser) {
        const { question, type, imgUrl, __user } = body
        const au = __user.userid
        if (!question) {
            throw new CoreException(CoreExceptionType.ERROR_CORE_HELP_CONTENT_MISSING)
        }
        const ct = timestampFormat()
        await this.globalHelpRepo.save(
            this.globalHelpRepo.create({
                question,
                type,
                imgUrl,
                au,
                ct,
            }),
        )
        return {}
    }
}
